﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using Business;
using TaskManager.Models;

namespace TaskManager.Controllers
{
    public class UploadController : Controller
    {
        //
        // GET: /Upload/

        public int AsyncUpload()
        {
            IFileStore _fileStore = new DiskFileStore();
            return _fileStore.SaveUploadedFile(Request.Files[0]);
        }

        public JsonResult Get(int id)
        {
            var document = DocumentBO.GetById(id);
            return Json(document != null ? document.Name : id.ToString(), JsonRequestBehavior.AllowGet);
        }

        public FileResult DownloadFile(int id)
        {
            var document = DocumentBO.GetById(id);
            if (document != null)
            {
                var _uploadsFolder = HostingEnvironment.MapPath("~/Uploads");

                byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(_uploadsFolder, document.FilePath));

                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, document.Name);
            }

            return null;
        }
    }
}
